package xyz.xiezc.spider.duplicate;


import cn.hutool.bloomfilter.BloomFilter;
import cn.hutool.bloomfilter.BloomFilterUtil;
import cn.hutool.setting.Setting;
import xyz.xiezc.ioc.annotation.Component;
import xyz.xiezc.ioc.annotation.InitMethod;
import xyz.xiezc.ioc.annotation.Inject;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author wb-xzc291800
 * @date 2019/04/17 15:17
 */
@Component
public class BitMapBloomFilter implements BloomFilter {


    private AtomicLong count = new AtomicLong(0);

    @Inject
    Setting setting;

    int size;

    BloomFilter bitSet;

    @InitMethod
    public void init() {
        size = setting.getInt("bloomFilter.size", "duplicate");
        bitSet = BloomFilterUtil.createBitSet(size* 2, size , 4);
    }

    public long getCount() {
        return count.get();
    }

    /**
     * 增加字符串到Filter映射中
     *
     * @param str 字符串
     */
    @Override
    public boolean add(String str) {
        boolean flag = bitSet.add(str);
        if (flag) {
            count.addAndGet(1);
        }
        return flag;
    }

    /**
     * 是否可能包含此字符串，此处存在误判
     *
     * @param str 字符串
     * @return 是否存在
     */
    @Override
    public boolean contains(String str) {
        return bitSet.contains(str);
    }
}
